package com.xx.sg.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xx.sg.exception.ServiceException;
import com.xx.sg.own.entity.LocalResource;
import com.xx.sg.own.entity.User;
import com.xx.sg.own.service.LocalResourceService;
import com.xx.sg.own.service.UserService;
import com.xx.sg.util.FileUploadUtils;
import com.xx.sg.util.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/localResource")
@Tag(name = "本地资源", description = "本地资源API")
public class LocalResourceController {

    @Autowired
    private LocalResourceService localResourceService;
    @Autowired
    private UserService userService;
    @Value("${sg.profile}")
    private String profile;

    @PostMapping(path = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "资源文件上传", description = "资源文件上传")
    public R importResource(@RequestParam("file") MultipartFile file,
                            @RequestParam String userId) {
        User user = userService.getById(userId);
        if (user == null) {
            throw new ServiceException("未查询到用户信息");
        }
        String filePath = FileUploadUtils.uploadFile(profile, "localResource", file);


        LocalResource localResource = LocalResource.builder()
                .userId(userId)
                .deptId(user.getDeptIds())
                .filePath(filePath)
                .initName(file.getOriginalFilename())
                .fileName(filePath.substring(filePath.lastIndexOf("/") + 1))
                .build();
        localResourceService.save(localResource);
        return R.success();
    }

    @GetMapping("/deleteResource/{id}")
    @Operation(summary = "删除指定部门的资源列表", description = "删除指定部门的资源列表")
    public R deleteResource(@PathVariable("id") String id) {
        localResourceService.removeById(id);
        return R.success();
    }

    @GetMapping("/deptResource/{userId}")
    @Operation(summary = "获取指定部门的资源列表", description = "获取指定部门的资源列表")
    public R deptResource(@PathVariable String userId) {
        User user = userService.getById(userId);
        LambdaQueryWrapper<LocalResource> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LocalResource::getDeptId, user.getDeptIds());
        List<LocalResource> list = localResourceService.list(wrapper);
        return R.success(list);
    }

}
